﻿using CarPCBATest.Procedure;
using Common;
using ControlzEx;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Markup.Localizer;
using VM.Core;
using VM.PlatformSDKCS;
using VMControls.Interface;
using WebServiceTool.WebReference1;
using static GerberLibrary.ArtWork.Functions.FlowerThing;

namespace CarPCBATest.ViewModel
{
    public partial class HomeViewModel : NotifyBase
    {
        public Action SNInputFocusAction;
        public Action<int> SNInputFocusSwitchAction;
        public Action<int> SNInputVisibilityAction;

        private bool vmPorjLoaded = false;
        public List<TestResultData> TestResultDatas { get; set; }
        public List<string> LocalLogs { get; set; }

        public STD_IN STD_IN { get; set; } = new STD_IN();
        public StarnetService WebClient { get; set; } = new StarnetService();

        private void ShowMessage(string msg, string msgType = "错误")
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                var mwin = Application.Current.MainWindow as MetroWindow;

                mwin.ShowMessageAsync(msgType, msg);
            });
        }

        private bool? _testResult;

        public bool? TestResult
        {
            get { return _testResult; }
            set
            {
                _testResult = value;
                this.DoNotify();
            }
        }

        public HomeViewModel()
        {
            ResetCountCommand = new CommandBase(ResetCount);
            SaveImageCommand = new CommandBase(SaveImage);
            StartCommand = new CommandBase(Start);
            ResetCommand = new CommandBase(Reset);
            LoadedCommand = new CommandBase(Loaded);
            UnloadedCommand = new CommandBase(Unloaded);
            TestResult = null;
            VmSolution.OnWorkStatusEvent += VmSolution_OnWorkStatusEvent;//工作执行状态回调
            VmSolution.OnSolutionLoadEndEvent += VmSolution_OnSolutionLoadEndEvent;
            VmSolution.OnSolutionLoadBeginEvent += VmSolution_OnSolutionLoadBeginEvent;

            MachineStatus = MachineStatus.Stop;
            IOModule.StartAction += StartAction;
            IOModule.EmgStopAction += EmgStopAction;
            IOModule.EmgCancelAction += EmgCancelAction;
        }

        private void ResetCount(object obj)
        {
            OKCount = 0;
            NGCount = 0;
        }

        private void VmSolution_OnSolutionLoadBeginEvent(ImvsSdkDefine.IMVS_SOLUTION_LOAD_BEGEIN_INFO solutionLoadBeginInfo)
        {
            vmPorjLoaded = false;
        }

        private void VmSolution_OnSolutionLoadEndEvent(ImvsSdkDefine.IMVS_SOLUTION_LOAD_END_INFO solutionLoadEndInfo)
        {
            try
            {
                VmSolution.Instance.SilentExecute();
            }
            catch (VmException vex)
            {
                Mylog.Error(vex, vex.Message);
                Log = vex.Message;
            }
            vmPorjLoaded = true;
        }

        private void SaveImage(object obj)
        {
            try
            {
                currentProcId = 10003;
                Stopwatch sw = Stopwatch.StartNew();
                for (int i = 0; i < 30; i++)
                {
                    Log = $"save[{i}]";
                    vmProcHaveExec = false;
                    VisionTool.RunProc("SaveImage");
                    while (!vmProcHaveExec) ;
                    Console.WriteLine("视觉执行耗时：" + sw.ElapsedMilliseconds);
                }
            }
            catch (Exception ex)
            {
                Log = ex.Message;
            }
        }

        private void EmgCancelAction()
        {
            switch (MachineStatus)
            {
                case MachineStatus.Running:
                    break;

                case MachineStatus.Stop:
                    break;

                case MachineStatus.EmgStop:
                    MachineStatus = MachineStatus.Stop;
                    break;

                default:
                    break;
            }
        }

        private void EmgStopAction()
        {
            switch (MachineStatus)
            {
                case MachineStatus.Running:
                    MachineStatus = MachineStatus.EmgStop;
                    break;

                case MachineStatus.Stop:
                    MachineStatus = MachineStatus.EmgStop;
                    break;

                case MachineStatus.EmgStop:
                    break;

                default:
                    break;
            }
        }

        private void StartAction()
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                Start(null);
            });
        }

        private PcbConfig _pcbConfig;

        public PcbConfig PcbConfig
        {
            get { return _pcbConfig; }
            set
            {
                if (value != null)
                {
                    VisionProjPath = value.VisionProjPath;
                }
                _pcbConfig = value;
                this.DoNotify();
            }
        }

        private string _visionProjPath;

        public string VisionProjPath
        {
            get { return _visionProjPath; }
            set
            {
                if (value != _visionProjPath & value != null)
                {
                    Log = $"加载视觉方案";
                    if (File.Exists(value))
                    {
                        Task.Run(() =>
                        {
                            try
                            {
                                VisionTool.LoadVMSolution(value);
                                Log = "加载视觉方案成功";
                                vmPorjLoaded = true;
                            }
                            catch (Exception ex)
                            {
                                Log = ex.Message;
                            }
                        });
                    }
                    else
                    {
                        Log = $"视觉方案不存在[{value}]";
                    }
                }
                _visionProjPath = value;
                this.DoNotify();
            }
        }

        private void Loaded(object obj)
        {
            var config = PcbConfigHelper.AllPcbConfig;
            PcbConfig = config.ListConfig.Where(t => t.No == config.UsingNo).ToList()[0];
            this.SNInputFocusSwitchAction.Invoke(0);
            if (config is not null)
            {
                WebClient.Url = config.WebServiceUrl;
            }
            if (PcbConfig is not null)
                SNInputVisibilityAction.Invoke(PcbConfig.ListLedCurrentConfig[0].StationCount);

            Task.Run(() =>
            {
                try
                {
                    var titile = PcbConfigHelper.Load().Title;
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        var mwin = Application.Current.MainWindow as MetroWindow;
                        mwin.Title = titile;
                    });

                    DM3058E.Connect();
                    IT6302A.Connect();
                    IOModule.Connect();

                    if (PcbConfig != null)
                    {
                        foreach (var power in PcbConfig.ListPowerConfig)
                        {
                            IT6302A.SetChannelOutput(power.ChannelIndex, power.IsActive);
                            IT6302A.SetVoltage(power.ChannelIndex, power.Voltage);
                            IT6302A.SetCurrent(power.ChannelIndex, power.Current);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log = ex.Message;
                    Mylog.Error(ex, ex.Message);
                }
            });
        }

        private void Unloaded(object obj)
        {
        }

        private void Reset(object obj)
        {
            try
            {
                DM3058E.Connect();
                IT6302A.Connect();
                IOModule.Connect();
                IOModule.SetDOValue(DODefine.AirReset, 0);
                IOModule.SetDOValue(DODefine.Power, 0);
                IOModule.SetDOValue(DODefine.NG, 0);
                IOModule.SetDOValue(DODefine.OK, 0);
                TestResult = null;

                SN0 = "";
                SN1 = "";
                SN2 = "";
                SN3 = "";
                SN4 = "";
                SN5 = "";
                SN0UploadMesResult = null;
                SN1UploadMesResult = null;
                SN2UploadMesResult = null;
                SN3UploadMesResult = null;
                SN4UploadMesResult = null;
                SN5UploadMesResult = null;

                this.SNInputFocusSwitchAction.Invoke(0);
            }
            catch (Exception ex)
            {
                Log = ex.Message;
            }
        }

        private string _sn0;

        public string SN0
        {
            get { return _sn0; }
            set
            {
                _sn0 = value;
                this.DoNotify();
                if (_sn0.Length >= PcbConfig.SNLength)
                    SNInputFocusSwitchAction?.Invoke(1);
            }
        }

        private bool? _sn0UploadMesResult;

        public bool? SN0UploadMesResult
        {
            get { return _sn0UploadMesResult; }
            set
            {
                _sn0UploadMesResult = value;
                this.DoNotify();
            }
        }

        private bool? _sn1UploadMesResult;

        public bool? SN1UploadMesResult
        {
            get { return _sn1UploadMesResult; }
            set
            {
                _sn1UploadMesResult = value;
                this.DoNotify();
            }
        }

        private bool? _sn2UploadMesResult;

        public bool? SN2UploadMesResult
        {
            get { return _sn2UploadMesResult; }
            set
            {
                _sn2UploadMesResult = value;
                this.DoNotify();
            }
        }

        private bool? _sn3UploadMesResult;

        public bool? SN3UploadMesResult
        {
            get { return _sn3UploadMesResult; }
            set
            {
                _sn3UploadMesResult = value;
                this.DoNotify();
            }
        }

        private bool? _sn4UploadMesResult;

        public bool? SN4UploadMesResult
        {
            get { return _sn4UploadMesResult; }
            set
            {
                _sn4UploadMesResult = value;
                this.DoNotify();
            }
        }

        private bool? _sn5UploadMesResult;

        public bool? SN5UploadMesResult
        {
            get { return _sn5UploadMesResult; }
            set
            {
                _sn5UploadMesResult = value;
                this.DoNotify();
            }
        }

        private string _sn1;

        public string SN1
        {
            get { return _sn1; }
            set
            {
                _sn1 = value;
                this.DoNotify();
                if (_sn1.Length >= PcbConfig.SNLength)
                    SNInputFocusSwitchAction?.Invoke(2);
            }
        }

        private string _sn2;

        public string SN2
        {
            get { return _sn2; }
            set
            {
                _sn2 = value;
                this.DoNotify();
                if (_sn2.Length >= PcbConfig.SNLength)
                    SNInputFocusSwitchAction?.Invoke(3);
            }
        }

        private string _sn3;

        public string SN3
        {
            get { return _sn3; }
            set
            {
                _sn3 = value;
                this.DoNotify();
                if (_sn3.Length >= PcbConfig.SNLength)
                    SNInputFocusSwitchAction?.Invoke(4);
            }
        }

        private string _sn4;

        public string SN4
        {
            get { return _sn4; }
            set
            {
                _sn4 = value;
                this.DoNotify();
                if (_sn4.Length >= PcbConfig.SNLength)
                    SNInputFocusSwitchAction?.Invoke(5);
            }
        }

        private string _sn5;

        public string SN5
        {
            get { return _sn5; }
            set
            {
                _sn5 = value;
                this.DoNotify();
            }
        }

        private int _okCount;

        public int OKCount
        {
            get { return _okCount; }
            set
            {
                _okCount = value;
                if (NGCount + value > 0)
                {
                    OKRate = Math.Round(100 * (OKCount) / ((double)(NGCount + value)), 2).ToString() + "%";
                }
                else
                {
                    OKRate = "";
                }
                this.DoNotify();
            }
        }

        private int _ngCount;

        public int NGCount
        {
            get { return _ngCount; }
            set
            {
                _ngCount = value;
                if (OKCount + value > 0)
                {
                    OKRate = Math.Round(100 * (OKCount) / ((double)(OKCount + value)), 2).ToString() + "%";
                }
                else
                {
                    OKRate = "";
                }
                this.DoNotify();
            }
        }

        private string _okRate;

        public string OKRate
        {
            get { return _okRate; }
            set
            {
                _okRate = value;
                this.DoNotify();
            }
        }

        private MachineStatus _machineStatus;

        public MachineStatus MachineStatus
        {
            get { return _machineStatus; }
            set { _machineStatus = value; }
        }

        private int count = 0;

        private void Start(object obj)
        {
            // 0 系统状态判定
            switch (MachineStatus)
            {
                case MachineStatus.Running:
                    return;

                case MachineStatus.Stop:
                    if (!IOModule.GetDIValue(DIDefine.SafeLight))
                    {
                        Log = "安全光栅感应";
                        IOModule.SetDOValue(DODefine.NG, 1);
                        return;
                    }
                    MachineStatus = MachineStatus.Running;
                    break;

                case MachineStatus.EmgStop:
                    Log = "设备处于急停状态";
                    IOModule.SetDOValue(DODefine.NG, 1);
                    return;

                default:
                    return;
            }

            Task.Run(() =>
            {
                try
                {
                    TestResult = null;

                    SN0UploadMesResult = null;
                    SN1UploadMesResult = null;
                    SN2UploadMesResult = null;
                    SN3UploadMesResult = null;
                    SN4UploadMesResult = null;
                    SN5UploadMesResult = null;
                    LocalLogs = new List<string>();

                    Log = "--------------------" + count++.ToString();
                    if (PcbConfig is null)
                    {
                        throw new Exception("测试方案不能为空");
                    }
                    int stationCount = PcbConfig.ListLedCurrentConfig[0].StationCount;
                    int snLength = PcbConfig.SNLength;
                    string ctlStyle = PcbConfig.CtlStyle;

                    #region 参数校验

                    // 探针使用次数校验
                    if (PcbConfig.ProbeMaxUsedTimes < PcbConfig.ProbeUsedTimes)
                    {
                        throw new Exception("探针使用次数超过预设值");
                    }

                    if (ctlStyle == "直流点灯")
                    {
                        if (PcbConfig.ListLedCurrentConfig.Count != 1)
                        {
                            throw new Exception("直流点灯只允许一条功能测试配置");
                        }
                    }
                    else if (ctlStyle == "通信控制")
                    {
                        if (PcbConfig.ListLedCurrentConfig.Where(x => x.StationCount != 1).Count() > 0)
                        {
                            throw new Exception("通信控制工位数量必须为1");
                        }
                    }
                    else
                    {
                        throw new Exception("无效的点灯控制类型");
                    }

                    #endregion 参数校验

                    #region SN校验

                    if (stationCount < 1 | stationCount > 6)
                    {
                        throw new Exception("请选择正确的工位数量");
                    }

                    if (SN0 == null | SN0 == "" | SN0.Length != snLength)
                    {
                        Log = ("工位1 SN码为空或长度异常");
                        MachineStatus = MachineStatus.Stop;

                        this.SNInputFocusSwitchAction.Invoke(0);
                        return;
                    }
                    if (stationCount > 1)
                    {
                        if (SN1 == null | SN1 == "" | SN1.Length != snLength)
                        {
                            Log = ("工位2 SN码为空或长度异常");
                            MachineStatus = MachineStatus.Stop;

                            this.SNInputFocusSwitchAction.Invoke(1);
                            return;
                        }
                    }

                    if (stationCount > 2)
                    {
                        if (SN2 == null | SN2 == "" | SN2.Length != snLength)
                        {
                            Log = ("工位3 SN码为空或长度异常");
                            MachineStatus = MachineStatus.Stop;

                            this.SNInputFocusSwitchAction.Invoke(2);
                            return;
                        }
                    }
                    if (stationCount > 3)
                    {
                        if (SN3 == null | SN3 == "" | SN3.Length != snLength)
                        {
                            Log = ("工位4 SN码为空或长度异常");
                            MachineStatus = MachineStatus.Stop;

                            this.SNInputFocusSwitchAction.Invoke(3);
                            return;
                        }
                    }
                    if (stationCount > 4)
                    {
                        if (SN4 == null | SN4 == "" | SN4.Length != snLength)
                        {
                            Log = ("工位5 SN码为空或长度异常");
                            MachineStatus = MachineStatus.Stop;

                            this.SNInputFocusSwitchAction.Invoke(4);
                            return;
                        }
                    }
                    if (stationCount > 5)
                    {
                        if (SN5 == null | SN5 == "" | SN5.Length != snLength)
                        {
                            Log = ("工位6 SN码为空或长度异常");
                            MachineStatus = MachineStatus.Stop;

                            this.SNInputFocusSwitchAction.Invoke(5);
                            return;
                        }
                    }

                    #endregion SN校验

                    if (!vmPorjLoaded)
                    {
                        Log = "请等待视觉方案加载完成";
                        MachineStatus = MachineStatus.Stop;

                        this.SNInputFocusSwitchAction.Invoke(0);
                        return;
                    }

                    TestResultDatas = new List<TestResultData>();

                    #region IO 初始化

                    IOModule.SetDOValue(DODefine.NG, 0);
                    IOModule.SetDOValue(DODefine.OK, 0);

                    #endregion IO 初始化

                    IOModule.SetDOValue(DODefine.Power, 0);
                    Log = "电源OFF";
                    //Thread.Sleep(5000);

                    {
                        //1 气缸下压
                        IOModule.SetDOValue(DODefine.AirReset, 1);
                        bool timeOut1 = false;
                        // 等待气缸到位
                        Task.Run(() =>
                        {
                            Thread.Sleep(5000);
                            timeOut1 = true;
                        });
                        while (true)
                        {
                            if (IOModule.GetDIValue(DIDefine.AirWork))
                            {
                                break;
                            }
                            if (timeOut1)
                            {
                                break;
                            }
                            Thread.Sleep(100);
                        }
                        if (timeOut1)
                        {
                            throw new Exception("等待气缸到位超时");
                        }
                        Log = "气缸到位";
                    }

                    // 更新探针使用次数
                    PcbConfig.ProbeUsedTimes += 1;
                    PcbConfigHelper.AllPcbConfig.ListConfig.Where(x => x.No == PcbConfig.No).ToArray()[0].ProbeUsedTimes = PcbConfig.ProbeUsedTimes;
                    PcbConfigHelper.Save();

                    //// 切换烧录模式
                    if (PcbConfig.BurnConfig.SubBurnConfigs.Where(x => x.IsBurn == true).Count() > 0)   //需要芯片烧录
                    {
                        //// 2 打开电源
                        Thread.Sleep(1000);
                        IOModule.SetDOValue(DODefine.Power, 1);
                        Log = "电源ON";
                        Thread.Sleep(100);

                        IOModule.SetDOValue(DODefine.LineSwitch, 1);
                        Log = "切换烧录模式";
                        Thread.Sleep(500);

                        // 3烧录
                        if (PcbConfig.BurnConfig.SubBurnConfigs != null)
                        {
                            if (PcbConfig.ChipType == "NSL21912")   //NSL21912 芯片烧录
                            {
                                foreach (var item in PcbConfig.BurnConfig.SubBurnConfigs)
                                {
                                    if (!item.IsBurn)
                                        continue;

                                    string checkCode = "";

                                    int newAddress = 0x00;
                                    bool ret = NSL21912.WriteFlash(PcbConfig.BurnConfig.Port, item.BrunFilePath, item.McuAddress, out newAddress);
                                    if (ret)
                                    {
                                        Log = $"芯片地址[{item.McuAddress}]烧录完成";
                                        LocalLogs.Add(Log);
                                    }
                                    else
                                    {
                                        foreach (var err in NSL21912.listErr)
                                        {
                                            Log = err;
                                        }
                                        Log = $"芯片地址[{item.McuAddress}]烧录失败";
                                        NGCount++;
                                        throw new Exception("测试失败");
                                    }
                                    IOModule.SetDOValue(DODefine.Power, 0);
                                    Log = "电源OFF";

                                    Thread.Sleep(2000);
                                    IOModule.SetDOValue(DODefine.Power, 1);
                                    Log = "电源ON";
                                    Thread.Sleep(1000);
                                    Log = "开始校验";
                                    bool ret2 = NSL21912.ReadFlash(PcbConfig.BurnConfig.Port, item.BrunFilePath, newAddress, out checkCode);

                                    Log = $"芯片校验码为:{checkCode}";
                                    LocalLogs.Add(Log);
                                    if (ret2)
                                    {
                                        Log = $"芯片地址[{item.McuAddress}]校验成功";
                                        LocalLogs.Add(Log);
                                    }
                                    else
                                    {
                                        foreach (var err in NSL21912.listErr)
                                        {
                                            Log = err;
                                        }
                                        Log = $"芯片地址[{item.McuAddress}]校验失败";
                                        NGCount++;
                                        throw new Exception("测试失败");
                                    }
                                }
                            }
                            else if (PcbConfig.ChipType == "TPS929120")
                            {
                                foreach (var item in PcbConfig.BurnConfig.SubBurnConfigs)
                                {
                                    if (!item.IsBurn)
                                        continue;

                                    string checkCode = "";

                                    int newAddress = 0x00;
                                    bool ret = TPS929120.WriteFlash(PcbConfig.BurnConfig.Port, item.BrunFilePath, item.McuAddress, out newAddress);
                                    if (ret)
                                    {
                                        Log = $"芯片地址[{item.McuAddress}]烧录完成";
                                        LocalLogs.Add(Log);
                                    }
                                    else
                                    {
                                        foreach (var err in TPS929120.listErr)
                                        {
                                            Log = err;
                                        }
                                        NGCount++;
                                        Log = $"芯片地址[{item.McuAddress}]烧录失败";
                                        LocalLogs.Add(Log);
                                        throw new Exception("测试失败");
                                    }
                                    Thread.Sleep(500);
                                    Log = "开始校验";
                                    bool ret2 = TPS929120.ReadFlash(PcbConfig.BurnConfig.Port, item.BrunFilePath, newAddress, out checkCode);

                                    Log = $"芯片校验码为:{checkCode}";
                                    LocalLogs.Add(Log);

                                    if (ret2)
                                    {
                                        Log = $"芯片地址[{item.McuAddress}]校验成功";
                                        LocalLogs.Add(Log);
                                    }
                                    else
                                    {
                                        foreach (var err in TPS929120.listErr)
                                        {
                                            Log = err;
                                        }
                                        Log = $"芯片地址[{item.McuAddress}]校验失败";
                                        LocalLogs.Add(Log);
                                        NGCount++;
                                        throw new Exception("测试失败");
                                    }
                                }
                            }
                        }
                        ///
                        //// 切换测试模式
                        IOModule.SetDOValue(DODefine.Power, value: 0);
                        Log = "电源OFF";
                        //IOModule.SetDOValue(DODefine.LineSwitch, 0);
                    }

                    IOModule.SetDOValue(DODefine.LineSwitch, 0);
                    Log = "切换测试模式";
                    Thread.Sleep(1000);

                    IOModule.SetDOValue(DODefine.Power, 1);

                    Log = "电源ON";
                    Thread.Sleep(1200);
                    Log = IOModule.GetDOValue(DODefine.LineSwitch) ? "烧录模式" : "测试模式";
                    Mylog.Debug($"测试模式：{IOModule.GetDOValue(DODefine.LineSwitch)}");

                    // 4视觉测试
                    bool result = true;
                    if (PcbConfig.CtlStyle == "通信控制")
                    {
                        PcbCANControl.Connect();
                    }
                    if (PcbConfig.ListLedCurrentConfig is not null)
                    {
                        if (PcbConfig.CtlStyle == "通信控制")
                        {
                            TestResultDatas.Add(new TestResultData
                            {
                                SN = SN0,
                            });
                            LocalLogs.Add($"工位1SN={SN0}");
                            foreach (var item in PcbConfig.ListLedCurrentConfig)
                            {
                                currentProcName = item.ProcName;
                                Type classType = typeof(HomeViewModel);
                                MethodInfo methodInfo = classType.GetMethod(item.TestMethodName);
                                if (methodInfo == null)
                                {
                                    throw new Exception($"测试方法未找到[{item.TestMethodName}]");
                                }
                                bool ret = (bool)methodInfo.Invoke(this, new object[] { item });
                                if (!ret)
                                {
                                    result = false;
                                }
                            }
                            TestResultDatas[0].IsOK = result;
                            if (result)
                            {
                                OKCount++;
                                Log = "测试OK";
                                TestResult = true;
                                IOModule.SetDOValue(DODefine.OK, 1);
                            }
                            else
                            {
                                NGCount++;
                                IOModule.SetDOValue(DODefine.NG, 1);
                                Log = "测试NG";
                                TestResult = false;
                            }
                        }
                        else if (PcbConfig.CtlStyle == "直流点灯")
                        {
                            var item = PcbConfig.ListLedCurrentConfig[0];
                            {
                                currentProcName = item.ProcName;
                                Type classType = typeof(HomeViewModel);
                                MethodInfo methodInfo = classType.GetMethod(item.TestMethodName);

                                for (int i = 0; i < item.StationCount; i++)
                                {
                                    PropertyInfo propertyInfo = classType.GetProperty($"SN{i}");
                                    LocalLogs.Add($"工位{i + 1}SN={propertyInfo.GetValue(this).ToString()}");
                                    TestResultDatas.Add(new TestResultData
                                    {
                                        SN = propertyInfo.GetValue(this).ToString()
                                    });
                                }

                                if (methodInfo == null)
                                {
                                    throw new Exception($"测试方法未找到[{item.TestMethodName}]");
                                }
                                bool ret = (bool)methodInfo.Invoke(this, new object[] { item });
                                if (!ret)
                                {
                                    result = false;
                                }
                            }
                            if (result)
                            {
                                OKCount++;
                                Log = "测试OK";
                                TestResult = true;
                                IOModule.SetDOValue(DODefine.OK, 1);
                            }
                            else
                            {
                                NGCount++;
                                IOModule.SetDOValue(DODefine.NG, 1);
                                Log = "测试NG";
                                TestResult = false;
                            }
                        }
                    }

                    if (PcbConfig.CtlStyle == "通信控制")
                        PcbCANControl.DisConnect();

                    // 发送测试日志到MES
                    if (PcbConfigHelper.AllPcbConfig.UploadMes)
                    {
                        try
                        {
                            int snIndex = 0;

                            Type classType = typeof(HomeViewModel);
                            foreach (var item in TestResultDatas)
                            {
                                PropertyInfo propertyInfo = classType.GetProperty($"SN{snIndex}UploadMesResult");

                                STD_IN.Update(item.SN, PcbConfigHelper.AllPcbConfig.Station, "", result, result ? "测试OK" : "测试NG", item.NgMsg.ToArray());
                                string inputXml = STD_IN.GenerateStringXml();
                                string outputXml = WebClient.DataService(PcbConfigHelper.AllPcbConfig.CallMethodName, inputXml);
                                var retData = STD_IN.ParseReturnXml(outputXml);
                                if (retData.Item1 == "0")   //调用webservice成功
                                {
                                    propertyInfo.SetValue(this, true);

                                    Log = $"工位[{snIndex + 1}]上传MES成功";
                                }
                                else
                                {
                                    propertyInfo.SetValue(this, false);
                                    Log = $"工位[{snIndex + 1}]上传MES失败：" + retData.Item2;
                                }
                                snIndex++;
                            }
                        }
                        catch (Exception ex)
                        {
                            Log = "Web Service 调用异常：" + ex.Message;
                            Mylog.Error(ex, ex.Message);
                        }
                    }
                    IOModule.SetDOValue(DODefine.Power, 0);
                    Log = "电源OFF";
                    Thread.Sleep(1200);
                    IOModule.SetDOValue(DODefine.AirReset, 0);
                    Log = "气缸复位";
                    Thread.Sleep(100);

                    if (result)
                    {
                        LocalLogs.Add("测试OK");
                    }
                    else
                    {
                        LocalLogs.Add("测试NG");
                    }

                    // 记录本地日志
                    {
                        string directory = Environment.CurrentDirectory + $"\\Data\\{DateTime.Now.ToString("yyyMMdd")}";
                        if (!Directory.Exists(directory))
                        {
                            Directory.CreateDirectory(directory);
                        }
                        string file = directory + "\\" + SN0 + DateTime.Now.ToString("yyyMMddHHmmss") + ".txt";
                        if (File.Exists(file))
                        {
                            File.Delete(file);
                        }
                        using (StreamWriter writer = new StreamWriter(file))
                        {
                            foreach (var item in LocalLogs)
                            {
                                writer.WriteLine(item);
                            }
                        }
                    }
                    if (false)
                    {
                        // 记录本地测试日志
                        foreach (var item in TestResultDatas)
                        {
                            TestResultData.Note(item);
                        }
                    }

                    SN0 = "";
                    SN1 = "";
                    SN2 = "";
                    SN3 = "";
                    SN4 = "";
                    SN5 = "";
                    this.SNInputFocusSwitchAction.Invoke(0);
                    MachineStatus = MachineStatus.Stop;
                    CameraTool.Close();
                }
                catch (Exception ex)
                {
                    CameraTool.Close();

                    PcbCANControl.DisConnect();
                    IOModule.SetDOValue(DODefine.Power, 0);
                    Log = "电源OFF";
                    Thread.Sleep(1200);
                    IOModule.SetDOValue(DODefine.AirReset, 0);
                    Log = "气缸复位";
                    Thread.Sleep(100);

                    IOModule.SetDOValue(DODefine.NG, 1);
                    Log = ex.Message;
                    TestResult = false;
                    Mylog.Error(ex, ex.Message);
                    SN0 = "";
                    SN1 = "";
                    SN2 = "";
                    SN3 = "";
                    SN4 = "";
                    SN5 = "";
                    this.SNInputFocusSwitchAction.Invoke(0);
                    MachineStatus = MachineStatus.Stop;
                }
            });
        }

        private string currentProcName;
        public CommandBase StartCommand { get; set; }
        public CommandBase ResetCommand { get; set; }
        public CommandBase UnloadedCommand { get; set; }
        public CommandBase LoadedCommand { get; set; }
        public CommandBase SaveImageCommand { get; set; }
        public CommandBase ResetCountCommand { get; set; }

        private void VmSolution_OnWorkStatusEvent(ImvsSdkDefine.IMVS_MODULE_WORK_STAUS workStatusInfo)
        {
            try
            {
                Mylog.Info($"procid[{workStatusInfo.nProcessID}],status[{workStatusInfo.nWorkStatus}]");
                if (workStatusInfo.nWorkStatus == 0 && workStatusInfo.nProcessID == currentProcId)//为0表示执行完毕，为1表示正在执行；10000表示流程1
                {
                    //通过流程获取结果
                    //VmProcedure vmProcess1 = (VmProcedure)VmSolution.Instance[currentProcName];
                    //String radiusResult = vmProcess1.ModuResult.GetOutputFloat("out").pFloatVal[0].ToString();
                    vmResult = VisionTool.GetGlobalVar("result");
                    vmProcHaveExec = true;
                    Console.WriteLine("视觉判断耗时" + swGlobal.ElapsedMilliseconds);
                }
            }
            catch (VmException ex)
            {
                Mylog.Error(ex, ex.Message);
                //ShowMessage(ex.Message);
            }
        }

        private string _log;
        private string vmResult;
        private bool vmProcHaveExec;

        public string Log
        {
            get { return _log; }
            set
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    _log = value;
                    this.DoNotify();
                }));
            }
        }
    }
}